// ==UserScript==
// @name		buymore
// @version		1.0.0
// @description	ErepMarket mass buy
// @author		Chuck
// @namespace   Erep
// @include		http://www.erepublik.com/hu/economy/market/*
// @include		http://www.erepublik.com/en/economy/market/*
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js
// @require     http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js
// @grant       GM_getValue
// @grant       GM_setValue
// @grant       GM_log
// ==/UserScript==

$('head').append("<link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery.ui.all.css' type='text/css' rel='stylesheet'>");
var amount = GM_getValue('BMAmount')*1;
var price = GM_getValue('BMMayPrice')*1;
var url = GM_getValue('BMUrl');

$('a.logout').before('<div id="buyMore">\
	<input id="BMAmount" value="100" size="6"><label for="BMAmount" >Amount</label><br/>\
	<input id="BMMayPrice" value="'+price+'" size="6"><label for="BMMayPrice" >MaxPrice</label><br/>\
	<div align="center"><button id="BMButton">Buy More</button></div><br/>\
	</div><a href="javascript:void(0)" id="buyMoreLink">BuyMore</a><br/>');	
GM_log('BM:'+$('#buyMore').size());
$('#buyMore').dialog({modal: true, autoOpen: false});
$('#buyMoreLink').click(function () {
	$('#buyMore').dialog('open');
});
$('#BMButton').button().click(function() {
	amount = $('#BMAmount').attr('value')*1;
	price = $('#BMMayPrice').attr('value')*1;
	GM_log('click:'+amount+':'+price+':'+url);
	if (amount>0 && price>0) {
		GM_log('prebuy');
		GM_setValue('BMAmount',amount);
		GM_setValue('BMMayPrice',""+price);
		GM_setValue('BMUrl',location.href);
		buy();
	} else {
		GM_log('badparam');
		
	}
});
GM_log('start:'+amount+':'+price+':'+url);
if (amount >0 && price > 0 && url == location.href) {
	var s = $('table.success_message td').text();
	GM_log('success:'+s);
	var a = s.replace(/.*bought\s+/,"").replace(/\sproduct.*/,"");
	GM_log('amount:'+a);
	amount -= a*1;
	GM_setValue('BMAmount',amount);
	if (amount >0) {
		buy();
	}
}

function buy() {
	GM_log('buy');
	var row = $('.price_sorted tr:first');
	var stock = $('td.m_stock',row).text()*1;
	var rowprice =  $('td.m_price',row).text().replace(/^\s+/,"").replace(/\s+\w{3}\s+$/,"")*1;
	GM_log('buy:'+(rowprice<=price)+":"+rowprice+":"+price);
	if (rowprice<=price) {
		var s = Math.min(stock, amount,9999);
		GM_log('stock:'+s);
		$('td.m_quantity input',row).attr('value',s);

		var offerId = parseInt($('.buyOffer',row).attr('id'));
        if (amount > 0 && offerId > 0) {
	        $("#offerId").val(offerId);
            $("#amount").val(s);
            $("#buyOffer").submit();
        }
	}
}